import { findElementByPlaceholder } from "./utils/find-element";

/** 判断字符传是否是Xpath表达式 */
const isXPath = (str: string): boolean => {
  const regex = /^([(/@]|id\()/;
  return regex.test(str);
}

/** 判断元素是否在页面展示 */
const isDisplay = (ele: HTMLElement): boolean => {
  return ele.style.display !== "none";
}

const getDocumentCtx = (): (Document | null) => {
    const documentCtxes: (Document | null)[] = [];
    documentCtxes.push(document);
    const windowProxyes: (WindowProxy | null)[] = [];
    const iframeElements = document.querySelectorAll("iframe");
    for(let iframeEle of iframeElements) {
      if(isDisplay(iframeEle)) {
        try {
          // 同源iframe
          let document = iframeEle.contentDocument;
          if(!document) {
            if(iframeEle.contentWindow) {
              document = iframeEle.contentWindow.document;
            }
            documentCtxes.push(document);
          }
        }catch(err) {
          // 非同源iframe         
          if(iframeEle.src.startsWith("http")){
             windowProxyes.push(iframeEle.contentWindow);
          }
        }
      }
    }

    return documentCtxes;
}

export default (selector: string) => {
    const documentCtxes = getDocumentCtx();
    for(let documentCtx of documentCtxes) {
      const ele = findElementByPlaceholder(selector, documentCtx, () => {

      });
      if(ele instanceof HTMLInputElement) {
        ele.classList.add("luhy-highlight");
        // ele.focus();
        ele.value = "13605305346";
       
      }
      console.log(ele);
    
    }

    iframeEle.contentWindow?.postMessage("输入密码", iframeEle.src);
    // for(let documentCtx of documents) {
    //   if(documentCtx) {
    //     const res = xpath({multiple: true, selector: xpathStr}, documentCtx);
    //     if(res) {
    //       return res;
    //     }
    //   } 
    // }
   
};